"""
简化测试脚本
测试系统核心功能，不依赖外部包安装
"""

import sys
import os

def test_imports():
    """测试模块导入"""
    print("测试模块导入...")
    
    try:
        # 测试基础模块
        import json
        import os
        from datetime import datetime
        print("[OK] 基础模块导入成功")
        
        # 测试自定义模块（如果可用）
        try:
            sys.path.append('.')
            from data.preprocessing import DataPreprocessor
            print("[OK] 数据预处理模块导入成功")
        except ImportError as e:
            print(f"[WARN] 数据预处理模块导入失败: {e}")
        
        try:
            from models.xgboost_model import XGBoostPredictor
            print("[OK] XGBoost模型模块导入成功")
        except ImportError as e:
            print(f"[WARN] XGBoost模型模块导入失败: {e}")
        
        try:
            from models.lstm_model import LSTMModelWrapper
            print("[OK] LSTM模型模块导入成功")
        except ImportError as e:
            print(f"[WARN] LSTM模型模块导入失败: {e}")
        
        try:
            from models.model_fusion import ModelFusion
            print("[OK] 模型融合模块导入成功")
        except ImportError as e:
            print(f"[WARN] 模型融合模块导入失败: {e}")
        
        try:
            from utils.shap_explainer import SHAPExplainer
            print("[OK] SHAP解释器模块导入成功")
        except ImportError as e:
            print(f"[WARN] SHAP解释器模块导入失败: {e}")
        
        try:
            from utils.intervention_recommender import InterventionRecommender
            print("[OK] 干预推荐器模块导入成功")
        except ImportError as e:
            print(f"[WARN] 干预推荐器模块导入失败: {e}")
        
        return True
        
    except Exception as e:
        print(f"[ERROR] 模块导入测试失败: {e}")
        return False

def test_file_structure():
    """测试文件结构"""
    print("\n测试文件结构...")
    
    required_files = [
        'app.py',
        'requirements.txt',
        'README.md',
        'models/__init__.py',
        'models/xgboost_model.py',
        'models/lstm_model.py',
        'models/model_fusion.py',
        'data/__init__.py',
        'data/preprocessing.py',
        'utils/__init__.py',
        'utils/shap_explainer.py',
        'utils/intervention_recommender.py',
        'templates/base.html',
        'templates/index.html',
        'templates/doctor_dashboard.html',
        'templates/user_dashboard.html'
    ]
    
    missing_files = []
    
    for file_path in required_files:
        if os.path.exists(file_path):
            print(f"[OK] {file_path}")
        else:
            print(f"[MISSING] {file_path}")
            missing_files.append(file_path)
    
    if missing_files:
        print(f"\n缺失文件: {len(missing_files)} 个")
        return False
    else:
        print(f"\n所有必需文件都存在: {len(required_files)} 个")
        return True

def test_basic_functionality():
    """测试基础功能"""
    print("\n测试基础功能...")
    
    try:
        # 测试数据预处理器
        sys.path.append('.')
        from data.preprocessing import DataPreprocessor
        
        preprocessor = DataPreprocessor()
        
        # 测试用户输入预处理
        user_data = {
            'age': 45,
            'gender': 'male',
            'height': 175,
            'weight': 75,
            'systolic_bp': 130,
            'diastolic_bp': 85,
            'blood_glucose': 105,
            'smoking': True,
            'family_history': False,
            'exercise_frequency': 'regularly'
        }
        
        processed_data = preprocessor.preprocess_user_input(user_data)
        print(f"[OK] 数据预处理功能正常: {len(processed_data)} 个特征")
        
        # 测试XGBoost模型
        from models.xgboost_model import XGBoostPredictor
        xgb_model = XGBoostPredictor()
        
        # 测试模拟预测
        prediction = xgb_model.predict(user_data)
        print(f"[OK] XGBoost预测功能正常: 综合风险 {prediction['overall_risk']['probability']:.3f}")
        
        # 测试LSTM模型
        from models.lstm_model import LSTMModelWrapper
        lstm_model = LSTMModelWrapper()
        
        prediction = lstm_model.predict(user_data)
        print(f"[OK] LSTM预测功能正常: 预测血压 {prediction['predicted_values']['systolic_bp']:.1f}")
        
        # 测试模型融合
        from models.model_fusion import ModelFusion
        fusion_model = ModelFusion(xgb_model, lstm_model)
        
        prediction = fusion_model.predict(user_data)
        print(f"[OK] 模型融合功能正常: 综合风险 {prediction['overall_risk']['probability']:.3f}")
        
        # 测试SHAP解释器
        from utils.shap_explainer import SHAPExplainer
        explainer = SHAPExplainer()
        
        explanation = explainer.explain_prediction(user_data, prediction)
        print(f"[OK] SHAP解释功能正常: {len(explanation['top_risk_factors'])} 个主要风险因素")
        
        # 测试干预推荐器
        from utils.intervention_recommender import InterventionRecommender
        recommender = InterventionRecommender()
        
        recommendations = recommender.get_recommendations(prediction, user_data)
        print(f"[OK] 干预推荐功能正常: {len(recommendations['lifestyle_interventions'])} 类建议")
        
        return True
        
    except Exception as e:
        print(f"[ERROR] 基础功能测试失败: {e}")
        return False

def test_web_templates():
    """测试Web模板"""
    print("\n测试Web模板...")
    
    try:
        # 检查模板文件内容
        templates = [
            'templates/base.html',
            'templates/index.html',
            'templates/doctor_dashboard.html',
            'templates/user_dashboard.html'
        ]
        
        for template in templates:
            if os.path.exists(template):
                with open(template, 'r', encoding='utf-8') as f:
                    content = f.read()
                    if len(content) > 100:  # 确保文件有内容
                        print(f"[OK] {template} (内容完整)")
                    else:
                        print(f"[WARN] {template} (内容较少)")
            else:
                print(f"[MISSING] {template}")
        
        return True
        
    except Exception as e:
        print(f"[ERROR] Web模板测试失败: {e}")
        return False

def main():
    """主函数"""
    print("慢性病风险预测系统 - 简化测试")
    print("=" * 50)
    print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    tests = [
        ("文件结构", test_file_structure),
        ("模块导入", test_imports),
        ("基础功能", test_basic_functionality),
        ("Web模板", test_web_templates)
    ]
    
    results = []
    
    for test_name, test_func in tests:
        try:
            result = test_func()
            results.append((test_name, result))
        except Exception as e:
            print(f"[ERROR] {test_name}测试异常: {e}")
            results.append((test_name, False))
    
    # 输出测试结果
    print("\n" + "=" * 50)
    print("测试结果汇总:")
    print("-" * 30)
    
    passed = 0
    for test_name, result in results:
        status = "[PASS]" if result else "[FAIL]"
        print(f"{test_name}: {status}")
        if result:
            passed += 1
    
    print(f"\n总计: {passed}/{len(results)} 个测试通过")
    
    if passed == len(results):
        print("\n[SUCCESS] 所有测试通过！系统核心功能正常。")
        print("\n下一步:")
        print("1. 安装依赖: pip install -r requirements.txt")
        print("2. 启动系统: python start_system.py")
        print("3. 访问: http://localhost:5000")
    else:
        print(f"\n[WARNING] 有 {len(results) - passed} 个测试失败，请检查相关模块。")
    
    return passed == len(results)

if __name__ == "__main__":
    from datetime import datetime
    success = main()
    sys.exit(0 if success else 1)
